<template>
  <div class="check-con" id="checkCon">
    <div class="right-content">
      <div style="display: flex;justify-content: flex-end;">
        <el-button type="primary" @click="handleDownload">
          导出为PDF
        </el-button>
      </div>

      <div class="check-info-pdf" id="printCon">
        <div class="pdf-mo" id="p26">
          <Tab000 :orgName='orgName' :orgId="props.currentRow.creditCode" :examineYear="props.currentRow.examineYear"/>
        </div>
        <div class="pdf-mo" id="p1">
          <Tab011 />
        </div>
        <div class="pdf-mo" id="p2">
          <Tab021 />
        </div>

        <div class="pdf-mo" id="p3">
          <Tab031 />
        </div>
        <div class="pdf-mo" id="p4">
          <Tab041 />
        </div>
        <div class="pdf-mo" id="p5">
          <Tab051 />
        </div>
        <div class="pdf-mo" id="p6">
          <Tab061 />
        </div>
        <div class="pdf-mo" id="p7">
          <Tab071 />
        </div>
        <div class="pdf-mo" id="p8">
          <Tab081 />
        </div>
        <div class="pdf-mo" id="p9">
          <Tab091 />
        </div>
        <div class="pdf-mo" id="p10">
          <Tab0101 />
        </div>
        <div class="pdf-mo" id="p11">
          <Tab0111 />
        </div>
        <div class="pdf-mo" id="p12">
          <Tab0121 />
        </div>
        <div class="pdf-mo" id="p13">
          <Tab0131 />
        </div>
        <div class="pdf-mo" id="p14">
          <Tab0141 />
        </div>
        <div class="pdf-mo" id="p15">
          <Tab0151 />
        </div>
        <div class="pdf-mo" id="p16">
          <Tab0161 />
        </div>
        <div class="pdf-mo" id="p17">
          <Tab0171 />
        </div>
        <div class="pdf-mo" id="p18">
          <Tab0181 />
        </div>
        <div class="pdf-mo" id="p19">
          <Tab0191 />
        </div>
        <div class="pdf-mo no-pd" id="p20">
          <Tab0201 />
        </div>
        <div class="pdf-mo" id="p21">
          <Tab0211 />
        </div>
        <div class="pdf-mo" id="p22">
          <Tab0221 />
        </div>
        <div class="pdf-mo" id="p23">
          <Tab0231 />
        </div>
        <div class="pdf-mo" id="p24">
          <Tab0241 />
        </div>
        <div class="pdf-mo" id="p25">
          <Tab0251 />
        </div>
      </div>
      <div>
        <img :src="myImgData" alt="">
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';


import { ref, reactive, nextTick, provide, onMounted } from 'vue'
import APTMethods from '@/api/yearCheck/mfOrg'
import Tab000 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab000.vue' //封面
import Tab011 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab011.vue' //基础信息
import Tab021 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab021.vue' //从业人员情况信息
//内部建设
import Tab031 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab031.vue' //负责人信息
import Tab041 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab041.vue' //理事会成员、监视情况信息
import Tab051 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab051.vue' //办事机构情况
import Tab061 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab061.vue' //内部建设情况
import Tab071 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab071.vue' //接受监督检查情况
import Tab081 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab081.vue' //开展公益活动情况
import Tab091 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab091.vue' //承接政府委托职能、购买服务项目、政府补贴情况
import Tab0101 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0101.vue' //国际合作情况
import Tab0111 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0111.vue' //对外交流、国际组织
import Tab0121 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0121.vue' //对外活动建议
import Tab0131 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0131.vue' //举办刊物及公益活动
import Tab0141 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0141.vue' //援藏援疆及乡村振兴活动,
import Tab0151 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0151.vue' //参与成渝经济圈建设情况
import Tab0161 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0161.vue' //年度工作报告
import Tab0171 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0171.vue' //年检审核意见

import Tab0181 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0181.vue' //现金流量表
import Tab0191 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0191.vue' //接受捐赠资助及使用
import Tab0201 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0201.vue' //
import Tab0211 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0211.vue' //参与成渝经济圈建设情况
import Tab0221 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0221.vue' //公益慈善活动支出
import Tab0231 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0231.vue' //党建情况
import Tab0241 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0241.vue' //上年度整改情况表
import Tab0251 from '@/views/yearCheck/checkResult/components/checkMF/checkItem/tab0251.vue' //附件材料

import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
const props = defineProps({
  currentRow: {
    type: Object,
    default: {}
  }
})


defineOptions({
  name: 'logManagement'
})

const emit = defineEmits(['openResult', 'openOpinion'])
const orgName = ref('')
const myImgData = ref('')
let elementList = []

orgName.value = props.currentRow.organizationBaseName

onMounted(() => {
  elementList = document.getElementsByClassName('pdf-mo');
})

const getDetailInfo = (index) => {
  const { creditCode, organizationType, id } = props.currentRow
  return new Promise((resolve, reject) => {
    APTMethods.getMFInfoByPage({
      id,
      organizationType,
      pageNumberMark: index - 0  //页码
    }).then((res) => {
      resolve(res)
    })
  })
}

// 提供方法给子组件
provide('getDetailInfo', { getDetailInfo });


// 函数：将指定元素渲染为图片，并添加到 PDF 中
async function addPageToPDF(element, pdf, pageNumber) {
  const canvas = await html2canvas(element);
  const imgData = canvas.toDataURL('image/png');
  if (pageNumber === 1) {
    // 第一页时，创建新的 PDF 页面
    pdf.addImage(imgData, 'PNG', 0, 0, pdf.internal.pageSize.getWidth(), pdf.internal.pageSize.getHeight());
    pdf.addPage();
  } else {
    // 其他页，继续在当前页添加内容
    pdf.addImage(imgData, 'PNG', 0, 0, pdf.internal.pageSize.getWidth(), pdf.internal.pageSize.getHeight());
  }
}

// 函数：导出多页 PDF
async function exportMultiPagePDF(elements) {
  const pdf = new jsPDF('p', 'mm', 'a4');
  for (let i = 0; i < elements.length; i++) {
    await addPageToPDF(elements[i], pdf, i + 1);
  }
  pdf.save('multi_page_document.pdf');
}


const handleDownload = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })

  const pdf = new jsPDF('p', 'mm', 'a4');
  setTimeout(async () => {
    // 遍历所有元素
    for (let index = 0; index < elementList.length; index++) {
      const element = elementList[index]
      // const element = document.getElementById(elementId);
      if (!element) return; // 如果元素不存在，跳过
      // 将元素转换为canvas
      await printPDF(element, pdf, index)
    }
    pdf.save('export.pdf');
    loading.close()
  }, 200)
};


const printPDF = (element, pdf, index) => {
  return new Promise<void>((resolve, reject) => {
    html2canvas(element, {
      useCORS: true,
      dpi: 200, // 设置截图的分辨率
      scale: 200 / 96, // 设置截图缩放比例，以适应pdf的dpi
      //html2canvas的配置项提供了一个回调函数 ignoreElements， 他的作用就是过滤节点的， html2canvas 他会对你的dom树进行循环，
      //每次循环都会调用一次 ignoreElements，ignoreElements接收一个参数就是当前循环到的dom,
      //当你返回true就不会循环这个节点的子节点了，意思就是过滤了当前节点，反之则保留当前节点继续向下循环。
      ignoreElements: e => {
        if (
          e.contains(element) ||
          element.contains(e) ||
          e.tagName === 'HEAD' ||
          (e.tagName === 'STYLE' && e.getAttribute('type') != 'text/css')
          // (e.tagName === 'LINK' && e.getAttribute('rel') == 'stylesheet') ||
          // e.getAttribute('data-html2canvas') != null // header里面的样式不能筛掉</div>
        ) {
          return false;
        } else {
          return true;
        }
      }
    }
    ).then(canvas => {
      console.log(index)
      const imgData = canvas.toDataURL('image/jpeg');
      // if (index == 0) myImgData.value = imgData
      // 如果不是第一页，添加新页
      if (index > 0) {
        pdf.addPage();
      }

      // 将canvas图片添加到PDF
      const imgProps = pdf.getImageProperties(imgData);
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
      pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);

      // 如果是最后一个元素，保存PDF
      // if (index === elementList.length - 1) {
      //   pdf.save('export.pdf');
      //   loading.close()
      // }
      resolve()
    });
  })
}

defineExpose({
  handleDownload
});


</script>

<style lang="scss" scoped>
.right-content {
  width: 100%;
}

::v-deep .el-dialog {
  margin-bottom: 0;
}

::v-deep .el-dialog__body {
  padding-top: 0 !important;
}

table.m-table {
  border-spacing: 0px;
  width: 100%;
  border-top: 1px solid #999;
  border-left: 1px solid #999;
  color: #000;

  thead {
    background: #f0f7fc;
    color: rgb(37, 43, 53);

    th {
      border-right: 1px solid #999;
      border-bottom: 1px solid #999;
      text-align: center;
      height: 32px;
    }
  }


  td {
    height: 32px;
    border-right: 1px solid #999;
    border-bottom: 1px solid #999;
    text-align: center;

    &.td-head {
      background: #f0f7fc;
    }
  }
}
</style>
<style lang="scss" scoped>
//隐藏滚轮
::v-deep .el-switch.is-disabled {
  opacity: 1;
}

::v-deep .el-descriptions__title {
  margin-top: 15px;
}

.check-con {
  width: 100%;
  // height: 500px;
  // padding: 0 50px;
  overflow: auto;
  box-sizing: border-box;
  display: flex;

  ::-webkit-scrollbar {
    width: 0;
  }

  //将宽度设为0，滚动条就会隐藏。
  ::-webkit-scrollbar {
    display: none;
  }

  .left-tree {
    width: 280px;
    padding: 20px;
    padding-left: 10px;
    padding-right: 10px;
    margin-right: 10px;
    font-size: 12px;
    box-sizing: border-box;
    height: 600px;
    overflow: auto;
    border: 1px solid #eee;
  }
}

.msg-tip {
  padding: 20px 0;
  color: #000;
  font-family: '微软雅黑';
}
</style>
